package io.renren.modules.xsl.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 薪事力XML转换工具类
 * 将JSON数据转换为标准XML格式
 */
public class XslXmlConverter {
    
    // Excel指标字段顺序定义
    private static final String[] EXCEL_FIELD_ORDER = {
        "ID", "ENT_INDUSTRY", "ENT_NAME", "ENT_CODE", "ENT_GNAME", "ENT_PNAME", 
        "PARENT_ID", "ENT_TYPE", "STATUS", "ORDER_NUM", "IS_DELETED", "IS_VIRTUAL",
        "PLATFORM_COUNTRY", "PLATFORM_SIZE", "PLATFORM_LISTED", "PLATFORM_COMPANY_NAME",
        "PLATFORM_REG_CODE", "PLATFORM_ORG_CODE", "PLATFORM_LEVEL", "PLATFORM_PROVINCE",
        "PLATFORM_CITY", "PLATFORM_INDUSTRY", "PLATFORM_SEQUENCE", "SALARY_MONTH"
    };
    
    // 字段映射配置 - 使用Map结构
    private static final Map<String, FieldConfig> FIELD_MAPPING = new HashMap<>();
    
    static {
        // 初始化字段映射配置
        FIELD_MAPPING.put("ID", new FieldConfig("orgId", "normal"));
        FIELD_MAPPING.put("ENT_INDUSTRY", new FieldConfig("name", "normal"));
        FIELD_MAPPING.put("ENT_NAME", new FieldConfig("name", "normal"));
        FIELD_MAPPING.put("ENT_CODE", new FieldConfig("orgCode", "normal"));
        FIELD_MAPPING.put("ENT_GNAME", new FieldConfig("groupName", "groupDefault"));
        FIELD_MAPPING.put("ENT_PNAME", new FieldConfig("groupName", "groupDefault"));
        FIELD_MAPPING.put("PARENT_ID", new FieldConfig("parentId", "normal"));
        FIELD_MAPPING.put("ENT_TYPE", new FieldConfig("typeFlag", "normal"));
        FIELD_MAPPING.put("STATUS", new FieldConfig("state", "normal"));
        FIELD_MAPPING.put("ORDER_NUM", new FieldConfig("orderNum", "normal"));
        FIELD_MAPPING.put("IS_DELETED", new FieldConfig("isDeleted", "normal"));
        FIELD_MAPPING.put("IS_VIRTUAL", new FieldConfig("isVirtual", "normal"));
        FIELD_MAPPING.put("PLATFORM_COUNTRY", new FieldConfig("platform_FwJJW1ur", "customField"));
        FIELD_MAPPING.put("PLATFORM_SIZE", new FieldConfig("platform_ZaNOO5mM", "customField"));
        FIELD_MAPPING.put("PLATFORM_LISTED", new FieldConfig("platform_KIDv1H8O", "customField"));
        FIELD_MAPPING.put("PLATFORM_COMPANY_NAME", new FieldConfig("platform_sEu60KCl", "customField"));
        FIELD_MAPPING.put("PLATFORM_REG_CODE", new FieldConfig("platform_HSu3FWmi", "customField"));
        FIELD_MAPPING.put("PLATFORM_ORG_CODE", new FieldConfig("platform_I9b6hyi9", "customField"));
        FIELD_MAPPING.put("PLATFORM_LEVEL", new FieldConfig("platform_tgzUSgTV", "customField"));
        FIELD_MAPPING.put("PLATFORM_PROVINCE", new FieldConfig("platform_JHz6gK5L", "customField"));
        FIELD_MAPPING.put("PLATFORM_CITY", new FieldConfig("platform_d3IX6EVI", "customField"));
        FIELD_MAPPING.put("PLATFORM_INDUSTRY", new FieldConfig("platform_C6vrL5oL", "customField"));
        FIELD_MAPPING.put("PLATFORM_SEQUENCE", new FieldConfig("platform_BReew6oM", "customField"));
        FIELD_MAPPING.put("SALARY_MONTH", new FieldConfig("salaryMonth", "autoGenerate"));
    }
    
    /**
     * 字段配置类
     */
    private static class FieldConfig {
        private final String jsonKey;
        private final String fieldType;
        
        public FieldConfig(String jsonKey, String fieldType) {
            this.jsonKey = jsonKey;
            this.fieldType = fieldType;
        }
        
        public String getJsonKey() {
            return jsonKey;
        }
        
        public String getFieldType() {
            return fieldType;
        }
    }
    
    /**
     * 将薪事力组织JSON数据转换为标准XML格式
     * @param jsonArray 薪事力组织JSON数组
     * @return 标准XML字符串
     */
    public static String convertOrganizationToXml(JSONArray jsonArray) {
        try {
            // 创建XML文档
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.newDocument();
            
            // 创建根元素 Package
            Element packageElement = doc.createElement("Package");
            doc.appendChild(packageElement);
            
            // 创建Head元素
            Element headElement = doc.createElement("Head");
            packageElement.appendChild(headElement);
            
            // 添加Head子元素
            Element resCaptionElement = doc.createElement("resCaption");
            resCaptionElement.setTextContent("职工薪资信息");
            headElement.appendChild(resCaptionElement);
            
            Element resCodeElement = doc.createElement("resCode");
            resCodeElement.setTextContent("SALARY_DETAIL_INFO");
            headElement.appendChild(resCodeElement);
            
            // 创建Records元素
            Element recordsElement = doc.createElement("Records");
            packageElement.appendChild(recordsElement);
            
            // 遍历JSON数组，为每个组织创建Record元素
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject orgObject = jsonArray.getJSONObject(i);
                
                // 创建Record元素
                Element recordElement = doc.createElement("Record");
                recordsElement.appendChild(recordElement);
                
                // 按照Excel指标字段顺序添加所有字段
                addAllFieldsInOrder(doc, recordElement, orgObject);
            }
            
            // 转换为XML字符串
            return documentToString(doc);
            
        } catch (Exception e) {
            throw new RuntimeException("XML转换失败", e);
        }
    }
    
    /**
     * 按照Excel指标字段顺序添加所有字段
     */
    private static void addAllFieldsInOrder(Document doc, Element parent, JSONObject org) {
        for (String xmlFieldName : EXCEL_FIELD_ORDER) {
            FieldConfig fieldConfig = FIELD_MAPPING.get(xmlFieldName);
            if (fieldConfig != null) {
                String jsonKey = fieldConfig.getJsonKey();
                String fieldType = fieldConfig.getFieldType();
                
                String fieldValue = getFieldValue(org, jsonKey, fieldType);
                addFieldAlways(doc, parent, xmlFieldName, fieldValue);
            }
        }
    }
    
    /**
     * 获取字段值
     */
    private static String getFieldValue(JSONObject org, String jsonKey, String fieldType) {
        switch (fieldType) {
            case "customField":
                JSONObject customFields = org.containsKey("customFields") ? 
                    org.getJSONObject("customFields") : new JSONObject();
                if (customFields.containsKey(jsonKey)) {
                    Object value = customFields.get(jsonKey);
                    return value != null ? value.toString() : "";
                }
                return "";
                
            case "autoGenerate":
                if ("salaryMonth".equals(jsonKey)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
                    return sdf.format(new Date());
                }
                return "";
                
            case "groupDefault":
                // ENT_GNAME和ENT_PNAME字段使用集团名称作为默认值
                // 查找集团记录（parentId为0的记录）
                return getGroupName(org);
                
            default:
                if (org.containsKey(jsonKey)) {
                    Object value = org.get(jsonKey);
                    return value != null ? value.toString() : "";
                }
                return "";
        }
    }
    
    /**
     * 获取集团名称
     */
    private static String getGroupName(JSONObject org) {
        // 如果当前记录就是集团（parentId为0），则使用自己的名称
        String parentId = org.getString("parentId");
        if ("0".equals(parentId)) {
            return org.getString("name");
        }
        
        // 否则返回"湖南医药发展投资集团"作为默认值
        return "湖南医药发展投资集团";
    }
    

    

    
    /**
     * 总是添加字段，即使没有值也要保留key
     */
    private static void addFieldAlways(Document doc, Element recordElement, String fieldName, String value) {
        Element fieldElement = doc.createElement(fieldName);
        if (value != null && !value.isEmpty()) {
            fieldElement.setTextContent(value);
        }
        // 即使没有值也要添加空元素
        recordElement.appendChild(fieldElement);
    }
    
    /**
     * 将Document对象转换为XML字符串
     */
    private static String documentToString(Document doc) {
        try {
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            
            // 设置XML格式
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
            
            StringWriter writer = new StringWriter();
            transformer.transform(new DOMSource(doc), new StreamResult(writer));
            
            return writer.toString();
        } catch (Exception e) {
            throw new RuntimeException("XML转换失败", e);
        }
    }
    
    /**
     * 测试方法
     */
    public static void main(String[] args) {
        // 创建测试JSON数据
        JSONArray testArray = new JSONArray();
        
        // 第一条为集团信息
        JSONObject group = new JSONObject();
        group.put("customFields", new JSONObject());
        group.put("orderNum", "0");
        group.put("deptRoles", new JSONObject());
        group.getJSONObject("deptRoles").put("depLeader", new JSONArray());
        group.getJSONObject("deptRoles").put("depLeader4charge", new JSONArray());
        group.getJSONObject("deptRoles").put("depMgr", new JSONArray());
        group.put("parentId", "5628262272371569605");
        group.put("orgId", "5628262272371569605");
        group.put("typeFlag", "group2");
        group.put("modifyTime", "2025-11-07 10:02:33");
        group.put("isDeleted", false);
        group.put("createTime", "2025-11-04 17:42:17");
        group.put("name", "湖南医药发展投资集团");
        group.put("id", "5628262272371569605");
        group.put("state", 0);
        group.put("isVirtual", 0);
        testArray.add(group);
        
        // 第二条为子公司信息
        JSONObject company1 = new JSONObject();
        JSONObject customFields1 = new JSONObject();
        customFields1.put("platform_FwJJW1ur", "CN-中国");
        customFields1.put("platform_ZaNOO5mM", "1-大型");
        customFields1.put("platform_KIDv1H8O", "4-非上市");
        customFields1.put("platform_sEu60KCl", "湖南医药集团");
        customFields1.put("platform_HSu3FWmi", "91430000MABYUH0Q04");
        customFields1.put("platform_I9b6hyi9", "91430000MABYUH0Q04");
        customFields1.put("platform_tgzUSgTV", "1-一级");
        customFields1.put("platform_JHz6gK5L", "160-湖南省");
        customFields1.put("platform_d3IX6EVI", "430100-长沙市");
        customFields1.put("platform_C6vrL5oL", "27-医药制造业");
        customFields1.put("platform_BReew6oM", "1");
        
        company1.put("customFields", customFields1);
        company1.put("orderNum", "001");
        company1.put("description", "");
        company1.put("deptRoles", new JSONObject());
        company1.getJSONObject("deptRoles").put("depLeader", new JSONArray());
        company1.getJSONObject("deptRoles").put("depLeader4charge", new JSONArray());
        company1.getJSONObject("deptRoles").put("depMgr", new JSONArray());
        company1.put("parentId", "5628262272371569605");
        company1.put("orgId", "5628262272371569605");
        company1.put("typeFlag", "company");
        company1.put("modifyTime", "2025-11-20 16:33:58");
        company1.put("isDeleted", false);
        company1.put("createTime", "2025-11-12 11:00:24");
        company1.put("orgCode", "0151000000011");
        company1.put("name", "湖南医药发展集团总部");
        company1.put("id", "8044219211919328570");
        company1.put("state", 0);
        company1.put("isVirtual", 0);
        testArray.add(company1);
        
        // 转换为XML
        String xml = convertOrganizationToXml(testArray);
        System.out.println(xml);
    }
}